package com.pignest.hotel.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.pignest.framework.dao.BaseHibernateDao;
import com.pignest.hotel.beans.Dictionary;
import com.pignest.hotel.dao.DictionaryDao;

@SuppressWarnings("unchecked")
public class DictionaryHibernateDao extends BaseHibernateDao implements DictionaryDao {
	
	@Override
	public String defaultOrderBy() {
		return "o.key asc";//, o.value asc
	}
	
	public boolean exists(String key, String value) {
		List l = getHibernateTemplate().find("from Dictionary where key=? and value=?", new Object[] {key, value});
		return l != null && !l.isEmpty();
	}

	@Override
	public void delete(final String key) {
		getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query = session.createQuery("delete from Dictionary as dict where dict.key=:key");
				query.setString("key", key);
				return query.executeUpdate();
			}
		});
	}

	@Override
	public List<Dictionary> getDictionaries(String key) {
		return getHibernateTemplate()
				.find("from Dictionary as dict where dict.key=? order by dict.id desc", key);
	}

	@Override
	public List<String> getKeys() {
		return (List<String>)getHibernateTemplate()
				.find("select distinct dict.key from Dictionary as dict");
	}

	@Override
	public List<String> getValues(String key) {
		return getHibernateTemplate()
				.find("select distinct dict.value from Dictionary as dict where dict.key=? order by dict.value asc ", key);
	}

	public List<String> getValuesByPerfix(String perfix) {
		return getHibernateTemplate()
				.find("select dict.value from Dictionary as dict where dict.key like ? order by dict.key asc ", perfix + '%');
	}
	
	public void deleteByPerfix(String perfix) {
		getHibernateTemplate().bulkUpdate("delete from Dictionary where key like ? ", perfix + '%');
	}
	
	@Override
	public int getCount(final String key) {
		return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				String hql = "select count * from Dictionary as dict where dict.key=:key";
				Query query = session.createQuery(hql);
				query.setString("key", key);
				return query.uniqueResult();
			}
		});
	}


}
